package main

import (
	"context"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	pb "grpc-microservice/proto"
	"log"
	"net"
)

// 定义结构体实现pb

type userServiceServer struct {
	pb.UnimplementedUserServiceServer
	users map[int32]*pb.User
}

//创建一个新的userServiceServer实例

func NewUserServiceServer() *userServiceServer {
	return &userServiceServer{
		users: map[int32]*pb.User{
			1: {Id: 1, Username: "user1", Email: "user1@gmail.com"},
			2: {Id: 2, Username: "user2", Email: "user2@gmail.com"},
			3: {Id: 3, Username: "user3", Email: "user3@gmail.com"},
		},
	}
}

func (s *userServiceServer) GetUser(ctx context.Context, req *pb.GetUserRequest) (*pb.GetUserResponse, error) {
	user, ok := s.users[req.Id]
	if !ok {
		return nil, grpc.Errorf(codes.NotFound, "User not found")
	}
	return &pb.GetUserResponse{User: user}, nil
}

func (s *userServiceServer) CreateUser(ctx context.Context, req *pb.CreateUserRequest) (*pb.CreateUserResponse, error) {
	// 模拟自增id
	newID := int32(len(s.users) + 1)
	newUser := &pb.User{
		Id:       newID,
		Username: req.Username,
		Email:    req.Email,
	}

	return &pb.CreateUserResponse{User: newUser}, nil
}

func main() {
	//监听端口
	lis, err := net.Listen("tcp", ":8080")
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
		return
	}

	// 创建 gRpc服务器
	grpcServer := grpc.NewServer()
	// 注册服务
	pb.RegisterUserServiceServer(grpcServer, NewUserServiceServer())

	log.Printf("server listening at %v", lis.Addr())

	if err := grpcServer.Serve(lis); err != nil {
		log.Fatalf("failed to serve: %v", err)
	}

}
